import logging
import threading
import datetime
import time
import os

class WatchDog:
    def __init__(self, limit_time=30, name='DOGNAME'):
        self.limit = limit_time
        self.last_time = datetime.datetime.now()
        self.last_time_lock = threading.Lock()
        self.name = name

        self.dog = threading.Thread(
            target=self.worker_fn,
            name="watchdog"
        )
        self.dog.start()

    def feed(self):
        """call this function is host thread"""
        now = datetime.datetime.now()
        with self.last_time_lock:
            self.last_time = now

    def worker_fn(self):
        while True:
            time.sleep(30)
            now = datetime.datetime.now()
            with self.last_time_lock:
                interval = (now - self.last_time).total_seconds()
            if interval > self.limit:
                logging.info('watch dog exit, name=%s' % self.name)
                os._exit(-1)